package com.miwzn.boot.component.interceptor;

import com.miwzn.comm.ResponseEntity;
import com.miwzn.comm.annotation.OperationLog;
import com.miwzn.comm.exception.BsRException;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Auther: wzn
 * @Date: 2018/6/4 11:33
 * @Description: 异常处理
 */
@RestControllerAdvice
public class ExceptionHandle {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 处理自定义异常
     */
    @OperationLog(operation = "系统-异常",content ="处理自定义异常")
    @ExceptionHandler(BsRException.class)
    public ResponseEntity handleRRException(BsRException e) {
        ResponseEntity r = new ResponseEntity();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        logger.error(e.getMessage(), e);
        return r;
    }

    @OperationLog(operation = "系统-异常",content ="数据库中已存在该记录")
    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return ResponseEntity.error("数据库中已存在该记录");
    }

    @OperationLog(operation = "系统-异常",content ="没有权限，请联系管理员授权")
    @ExceptionHandler(AuthorizationException.class)
    public ResponseEntity handleAuthorizationException(AuthorizationException e) {
        logger.error(e.getMessage(), e);
        return ResponseEntity.error(HttpStatus.UNAUTHORIZED.value(),"没有权限，请联系管理员授权");
    }

    @OperationLog(operation = "系统-异常",content ="系统异常")
    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return ResponseEntity.error();
    }
}